<template>
	<view class="user-detail-container">
		<!-- 顶部头像区域 -->
		<view class="user-header">
			<view class="avatar-container" @click="chooseImage">
				<image class="avatar" :src="this.url || '/static/default-avatar.png'" mode="aspectFill"></image>
				<view class="avatar-edit-icon">+</view>
			</view>
			<view class="user-name">
				<input v-model="userData.username" class="name-input" placeholder="请输入用户名" />
			</view>
		</view>

		<!-- 用户信息列表 -->
		<view class="info-list">
			<view class="info-item">
				<text class="info-label">邮箱</text>
				<input v-model="userData.email" class="info-input" placeholder="请输入邮箱" />
			</view>

			<view class="info-item">
				<text class="info-label">电话</text>
				<input v-model="userData.phone" class="info-input" placeholder="请输入电话" type="number" />
			</view>

			<view class="info-item">
				<text class="info-label">性别</text>
				<picker @change="bindGenderChange" :value="genderIndex" :range="genderList" class="info-picker">
					<view class="picker">{{genderList[genderIndex] || '选择性别'}}</view>
				</picker>
			</view>

			<view class="info-item">
				<text class="info-label">生日</text>
				<picker mode="date" :value="this.birthday" @change="bindDateChange" class="info-picker">
					<view class="picker">{{this.birthday || '选择生日'}}</view>
				</picker>
			</view>

			<!-- <view class="info-item">
	        <text class="info-label">注册日期</text>
	        <text class="info-value">{{userData.createdAt}}</text>
	      </view> -->
		</view>

		<!-- 底部保存按钮 -->
		<view class="action-buttons">
			<button type="primary" @click="saveProfile" :loading="isSaving">保存修改</button>
		</view>
	</view>
</template>

<script>
	import base from "/axios/base.js";
	import {
		updateData,
		upFile
	} from '@/axios/http';
	export default {
		data() {
			return {
				userData: {}, //表单修改数据发送给后端需要与后端接收的实体类一致
				userInfo: {}, //原始数据不修改

				isSaving: false,
				isUploading: false,
				url: "",//拼接后的请求图片位置
				genderList: ['男', '女'],
				genderIndex: 0,
				birthday: '',
			}
		},
		onLoad() {
			// 获取 Cookie
			const cookieValue = uni.getStorageSync('LoginUser');
			this.userData = cookieValue;
			// 初始化头像地址
			this.url = base.url + this.userData.avatarUrl;
			//将userInfo对象中的属性初始化
			this.userInfo = this.userData;
			// 初始化性别选择器e
			this.genderIndex = this.userData.gender == 'male' ? 0 : 1;

			// 将ISO字符串转换为Date对象
			const date = new Date(this.userData.birthday);
			// 使用toISOString方法并截取字符串的前10个字符（即日期部分）
			this.birthday = date.toISOString().slice(0, 10);

			if (!cookieValue) {
				console.log("未登录！");
				// 注册成功后跳转到登录页面
				uni.showToast({
					title: '请登录',
					icon: 'error',
					duration: 1000
				});
				setTimeout(() => {
					// 跳转到登录页面
					uni.redirectTo({
						url: '/pages/login/login'
					});
				}, 1000);
			}
		},
		methods: {
			//选择图片
			chooseImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						this.uploadImage(tempFilePaths[0]);
					}
				});
			},
			// 上传图片到服务器
			async uploadImage(filePath) {
				this.isUploading = true;

				try {
					const res = await upFile('/upload',filePath);
					// 使用 JSON.parse() 将 JSON 字符串转换为对象
					const resObject = JSON.parse(res.data);
					if (resObject.code === 200) {
						//将返回的url给this.userData
						this.userData.avatarUrl = resObject.url;
						//更新头像url
						this.url = base.url + this.userData.avatarUrl;
						
						uni.showToast({
							title: '头像上传成功',
							icon: 'success'
						});
					} else {
						throw new Error(resObject.message || '上传失败');
					}
				} catch (error) {
					uni.showToast({
						title: '头像上传失败: ' + error.message,
						icon: 'none'
					});
				} finally {
					this.isUploading = false;
				}
			},
			//修改性别
			bindGenderChange(e) {
				this.genderIndex = e.detail.value;
				console.log("parseInt(e.detail.value):", parseInt(e.detail.value));
				this.userData.gender = parseInt(e.detail.value) == 0 ? 'male' : 'female';
				console.log("修改性别后", this.userData)
			},
			//修改生日
			bindDateChange(e) {
				this.userData.birthday = this.formatDate(e.detail.value);
				console.log("修改生日后", this.userData)
				// 将ISO字符串转换为Date对象
				const date = new Date(this.userData.birthday);
				// 使用toISOString方法并截取字符串的前10个字符（即日期部分）
				this.birthday = date.toISOString().slice(0, 10);
			},

			//截取年月日作为显示
			formatDateYMD(isoString) {
				// 将ISO字符串转换为Date对象
				const date = new Date(isoString);
				// 使用toISOString方法并截取字符串的前10个字符（即日期部分）
				return date.toISOString().slice(0, 10);
			},

			//日期格式化   Date对象转换成字符串
			formatDate(dateString) {
				const date = new Date(dateString);
				if (isNaN(date.getTime())) {
					console.error('Invalid date:', dateString);
					return '';
				}
				console.log(date);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}T00:00:00`;
			},
			//保存按钮
			async saveProfile() {
				if (this.isSaving) return;

				this.isSaving = true;
				//将日期格式化
				const formattedDate = this.formatDate(this.userData.birthday);
				console.log(formattedDate);
				this.userData.birthday = formattedDate;

				// 将对象转换为 JSON 字符串
				const jsonString = JSON.stringify(this.userData, null, 2);
				console.log("转化成json的对象", jsonString);
				try {
					const response = await updateData('/updateUser', jsonString); // 调用封装的 PUT 请求
					console.log("response", response);
					//如果更新不成功
					if (response.data.code != 200) {
						uni.showToast({
							title: response.data.message,
							icon: "error",
							duration: 2000
						});
					} else { //成功后重新设置用户cookie
						uni.setStorageSync('LoginUser', response.data.updateUser);
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				} finally {
					this.isSaving = false;
				}
			}
		}
	}
</script>

<style>
	.user-detail-container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;

		/* 新增头像容器样式 */
		.avatar-container {
			position: relative;
			width: 160rpx;
			height: 160rpx;
			margin-bottom: 20rpx;

			.avatar {
				width: 100%;
				height: 100%;
				border-radius: 50%;
				border: 2rpx solid #eee;
			}

			.avatar-edit-icon {
				position: absolute;
				right: 0;
				bottom: 0;
				width: 40rpx;
				height: 40rpx;
				background-color: #007AFF;
				color: white;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
			}
		}

		.user-header {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 40rpx 0;
			background-color: #fff;
			border-radius: 16rpx;
			margin-bottom: 20rpx;

			.avatar {
				width: 160rpx;
				height: 160rpx;
				border-radius: 50%;
				margin-bottom: 20rpx;
				border: 2rpx solid #eee;
			}

			.user-name {
				font-size: 36rpx;
				font-weight: bold;

				.name-input {
					text-align: center;
					font-size: 36rpx;
					font-weight: bold;
					color: #333;
				}
			}
		}

		.info-list {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 0 30rpx;

			.info-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx 0;
				border-bottom: 1rpx solid #f0f0f0;

				&:last-child {
					border-bottom: none;
				}

				.info-label {
					color: #666;
					font-size: 28rpx;
					width: 150rpx;
				}

				.info-input {
					flex: 1;
					text-align: right;
					font-size: 28rpx;
					color: #333;
					padding: 10rpx 0;
				}

				.info-picker {
					flex: 1;
					text-align: right;

					.picker {
						color: #333;
						font-size: 28rpx;
						padding: 10rpx 0;
					}
				}

				.info-value {
					color: #999;
					font-size: 28rpx;
				}
			}
		}

		.action-buttons {
			margin-top: 40rpx;
			padding: 0 30rpx;

			button {
				width: 100%;
			}
		}
	}
</style>